package xyz.xtgl.security.springboot.service.impl;

import xyz.xtgl.security.springboot.authentication.agent.AgentUserDetailsService;
import xyz.xtgl.security.springboot.authentication.merchant.MerchantUserDetailsService;
import xyz.xtgl.security.springboot.dao.UserDao;
import xyz.xtgl.security.springboot.entity.CustomUserDetails;
import xyz.xtgl.security.springboot.entity.User;
import common.core.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @created 2019-12-13 17:57
 * 根据用户名获取用户信息
 * 登录信息获取
 */
@Slf4j
@Service
public class CustomUserDetailsServiceImpl implements MerchantUserDetailsService , AgentUserDetailsService {

    @Autowired
    private UserDao userDao;
    /**
     * 商户平台登录
     * @param usernameOrPhone 用户名或者手机号码
     * @return CustomUserDetails
     * @throws UsernameNotFoundException
     */
    @Override
    public CustomUserDetails loadMerchantUserByUsernameOrPhone(String usernameOrPhone) throws UsernameNotFoundException {
        log.info("商户平台登录:{}",usernameOrPhone);
        return new CustomUserDetails("zhangsan","1");
    }

    /**
     * 代理商平台登录
     * @param usernameOrPhone 用户名或者手机号码
     * @return CustomUserDetails
     * @throws UsernameNotFoundException
     */
    @Override
    public CustomUserDetails loadAgentUserByUsernameOrPhone(String usernameOrPhone) throws UsernameNotFoundException {
        log.info("代理商平台登录:{}",usernameOrPhone);
        return new CustomUserDetails("wangwu","2");
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userDao.getUserByusername(username);
        if(CommonUtil.isEmpty(user)){
            return null;
        }
        List<String> list = userDao.findPermissionsByUserId(user.getId());
        List<GrantedAuthority> authorities= new ArrayList<>();
        if(CommonUtil.isNotEmpty(list)){
            list.forEach(row->{
                authorities.add(new SimpleGrantedAuthority(row));
            });
        }
        CustomUserDetails userDetails = new CustomUserDetails(user.getUsername(),user.getPassword()
                , authorities);

        return userDetails;
    }
}
